package de.msspp.btservice;

import java.util.ArrayList;
import java.util.Set;

import de.bluetooth.service.BluetoothClient;
import de.bluetooth.service.BluetoothClientP2P;
import de.bluetooth.service.BluetoothServer;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BluetoothService extends Activity implements OnClickListener {
	
	// Intent request codes
    private static final int REQUEST_ENABLE_BT = 2;
    private static final int REQUEST_DIALOG = 3;
    private static final int RESULT_CONNECT=4;
    private static final int RESULT_DISCONNECT=5;
	
	BluetoothAdapter mBluetoothAdapter;
	BluetoothDeviceAdapter mPairedDevicesAdapter;
	BluetoothDeviceAdapter mNewDevicesAdapter;
	BluetoothDeviceAdapter mConnectedDevicesAdapter;
	BroadcastReceiver mReceiver;	
	Button scanButton;
	ListView mPairedListView;
	ListView mNewDevicesListView;
	ListView mConnectedDevicesListView;
	
	BluetoothClientP2P client;
	
	//Shows our Toast-Message from other Threads
	Handler mToastHandler = new Handler(){
		@Override
		public void handleMessage(Message m) {
		Toast.makeText(getBaseContext(), m.obj.toString(), Toast.LENGTH_LONG).show();
		}
	};
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        scanButton = (Button)findViewById(R.id.button_scan);
        scanButton.setOnClickListener(this);
        
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        
		 client = new BluetoothClientP2P(mToastHandler, "TestService");
		 client.start();
        
        if(mBluetoothAdapter != null){
        	
        	//Bluetooth not enabled, start request to enable it
    		if (!mBluetoothAdapter.isEnabled()) 
    		{
    		    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    		    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    		}
    		
    		setupBT();
    		
    		// Initialize array adapters. One for already paired devices and
            // one for newly discovered devices
            mPairedDevicesAdapter = new BluetoothDeviceAdapter(this, R.layout.row, new ArrayList<BluetoothDevice>());
            mNewDevicesAdapter = new BluetoothDeviceAdapter(this, R.layout.row, new ArrayList<BluetoothDevice>());
            mConnectedDevicesAdapter = new BluetoothDeviceAdapter(this, R.layout.row, new ArrayList<BluetoothDevice>());
        	
        	OnItemClickListener listener = new OnItemClickListener()
    		{
    			 public void onItemClick(AdapterView<?> parent, View view,int position, long id)
    			 {
    				 Intent startDialog = new Intent(getApplicationContext(), Dialog.class);
    				 BluetoothDevice selected = mPairedDevicesAdapter.getItem(position);
    				 startDialog.putExtra("device", selected);
    				 startActivityForResult(startDialog, REQUEST_DIALOG);
    			 }
    		};
    		
    		mPairedListView = (ListView)findViewById(R.id.paired_devices);
    		mPairedListView.setAdapter(mPairedDevicesAdapter);
    		mPairedListView.setOnItemClickListener(listener);
    		
    		mNewDevicesListView = (ListView)findViewById(R.id.new_devices);
    		mNewDevicesListView.setAdapter(mNewDevicesAdapter);
    		mNewDevicesListView.setOnItemClickListener(listener);
    		
    		mConnectedDevicesListView = (ListView)findViewById(R.id.connected_devices);
    		mConnectedDevicesListView.setAdapter(mConnectedDevicesAdapter);
    		mConnectedDevicesListView.setOnItemClickListener(listener);
    		
    		
    		// Get a set of currently paired devices
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            
         // If there are paired devices, add each one to the ArrayAdapter
            if (pairedDevices.size() > 0) {
                findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
                for (BluetoothDevice device : pairedDevices) {
                    mPairedDevicesAdapter.add(device);
                }
            }

        	
        	//BluetoothServer srv = new BluetoothServer(new Handler(), mBluetoothAdapter, "Test");
        	//srv.start();
        	
        }
        
    }
    
    private void setupBT(){
    	// Create a BroadcastReceiver for ACTION_FOUND
		 mReceiver = new BroadcastReceiver() {
		    public void onReceive(Context context, Intent intent) {
		        String action = intent.getAction();
		        // When discovery finds a device
		        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
		            // Get the BluetoothDevice object from the Intent
		            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
		            // Add the name and address to an array adapter to show in a ListView
		            if(!mNewDevicesAdapter.contains(device)){
		            	mNewDevicesAdapter.add(device);
		            	mNewDevicesAdapter.notifyDataSetChanged();
		            }
		        }
		        else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
		        	//no devices found
		        	if(mNewDevicesAdapter.getCount() == 0)
		        		Toast.makeText(getApplicationContext(), "No devices found!", Toast.LENGTH_SHORT).show();
		        }
		    }
		};
		// Register the BroadcastReceiver
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		// Don't forget to unregister during onDestroy
		registerReceiver(mReceiver, filter); 
		filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(mReceiver, filter);
    }
    
    private void scan(){
    	if(!mBluetoothAdapter.isDiscovering())
		{
    		mNewDevicesAdapter.clear();
    		mNewDevicesAdapter.notifyDataSetChanged();
			mBluetoothAdapter.startDiscovery();
			Toast.makeText(this, "Scanning", Toast.LENGTH_LONG).show();
		}
    }
    
    
    @Override
    public void onResume(){
    	
    	super.onResume();
    	
    	// Register the BroadcastReceiver
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		// Don't forget to unregister during onDestroy
		registerReceiver(mReceiver, filter); 
		filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(mReceiver, filter);
    }
    
    @Override
    public void onPause(){
    	super.onPause();
    	Log.i("BluetoothService: ", "onPause: unregistering Receivers.");
    	unregisterReceiver(mReceiver);
    }
    
    @Override
    public void onStop(){
    	super.onStop();
    }

	@Override
	public void onClick(View v) {
		if(v.equals(scanButton)){
			scan();
			TextView tv = (TextView)findViewById(R.id.title_new_devices);
			tv.setVisibility(View.VISIBLE);
			mNewDevicesListView.setVisibility(View.VISIBLE);
		}
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ENABLE_BT: {
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) {
				// Bluetooth is now enabled, so set up a chat session
				Toast.makeText(
						this,
						"Bluetooth successfully enabled. Ready to establish a connection.",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(this, "Bluetooth not enabled. Quitting App.",
						Toast.LENGTH_LONG).show();
				finish();
			}

		}
			break;
		case REQUEST_DIALOG: {
			if(resultCode == Activity.RESULT_OK){
				client.sendMessage(data.getExtras().getString("message"));
			}
			else if(resultCode == RESULT_CONNECT){
				BluetoothDevice device =(BluetoothDevice) data.getExtras().get("device");
				client.connectToDevice(device);
			}
			else if(resultCode == RESULT_DISCONNECT){
				client.cancel();
			}
		}
			break;
		}

	}
}